package com.atxyj.springsecurity.security.common.utils;

import com.atxyj.springsecurity.security.common.constants.SecurityConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import javax.crypto.SecretKey;
import javax.xml.bind.DatatypeConverter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xieyujiao
 * @description Jwt工具类
 * @date 2021/7/29
 */
public class JwtTokenUtils {

    /**
     * 生成足够的安全随机密钥，以适合符合规范的签名
     */
    private static final byte [] API_KEY_SECRET_BYTES = DatatypeConverter.parseBase64Binary(SecurityConstants.JWT_SECRET_KEY);
    //todo 使用hmac算法对API_KEY_SECRET_BYTES进行加密
    private static final SecretKey SECRET_KEY = Keys.hmacShaKeyFor(API_KEY_SECRET_BYTES);

    public static String createToken (String username, String id , List<String> roles, boolean isRememberMe) {
        //todo 判断是否isRememberMe 如果为true 那么过期时间则为七天。false则为1小时
        long expiration = isRememberMe ? SecurityConstants.EXPIRATION_REMEMBER : SecurityConstants.EXPIRATION;
        final Date createdDate = new Date();
        final Date expirationDate = new Date(createdDate.getTime() + expiration * 1000);
        String tokenPrefix = Jwts.builder()
                .setHeaderParam("type" , SecurityConstants.TOKEN_TYPE)
                .signWith(SECRET_KEY, SignatureAlgorithm.ES256)
                .claim(SecurityConstants.ROLE_CLAIMS, String.join("," ,roles))
                .setId(id)
                //todo 设置发行人
                .setIssuer("xyj")
                //todo 设置发布日期
                .setIssuedAt(createdDate)
                .setSubject(username)
                .setExpiration(expirationDate)
                .compact();
        // 添加 token 前缀 "Bearer "
        return SecurityConstants.PREFIX + tokenPrefix ;
    }

    public static String getId(String token) {
        Claims claims = getClaims(token);
        return claims.getId();
    }

    public static UsernamePasswordAuthenticationToken getAuthentication(String token) {
        Claims claims = getClaims(token);
        List<SimpleGrantedAuthority> authorities = getAuthorities(claims);
        String username = claims.getSubject();
        return new UsernamePasswordAuthenticationToken(username, token , authorities );
    }

    private static List<SimpleGrantedAuthority> getAuthorities (Claims claims) {
     String role = (String)  claims.get(SecurityConstants.ROLE_CLAIMS);
     return Arrays.stream(role.split(",")).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    }

    public static Claims getClaims(String token) {
        return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
    }





}

